package cn.jinjimi.app.main.activity;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.CollectionUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.entity.Account;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.MyGridView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by haner on 15-1-26.
 */
public class PersonalTagActivity extends ToolBarCommonActivity
        implements AdapterView.OnItemClickListener {
    private List<String> allTags;
    private List<String> selectTags;
    private MyGridView gv;
    private EditText addTagEt;
    private KnoTagsAdapter adapter;
    private LinearLayout knotageditLl;
    private TextView[] tagArr;
    private View addTag;
    private TextView tag0;
    private TextView tag1;
    private TextView tag2;
    private InputMethodManager imm;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_personal_tag);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        setTitle(getString(R.string.info_tag));
        setRightText(R.string.save);
        allTags = new ArrayList<String>();
        selectTags = new ArrayList<String>();
        selectTags = getOriginTag();

        allTags.add(getString(R.string.tag_ensure));
        allTags.add(getString(R.string.tag_financial));
        allTags.add(getString(R.string.tag_baby));
        allTags.add(getString(R.string.tag_child));
        allTags.add(getString(R.string.tag_reserve));
        allTags.add(getString(R.string.tag_medical));
        allTags.add(getString(R.string.tag_complex));
        allTags.add(getString(R.string.tag_couple));
        allTags.add(getString(R.string.tag_personal));

        tag0 = (TextView) findViewById(R.id.tv_tag_0);
        tag1 = (TextView) findViewById(R.id.tv_tag_1);
        tag2 = (TextView) findViewById(R.id.tv_tag_2);

        tagArr = new TextView[]{tag0, tag1, tag2};

        gv = (MyGridView) findViewById(R.id.gv);
        addTagEt = (EditText) findViewById(R.id.et_add_tag);
        knotageditLl = (LinearLayout) findViewById(R.id.kno_tag_edit_ll);
        addTag = findViewById(R.id.tv_tag_add);

        adapter = new KnoTagsAdapter();
        gv.setAdapter(adapter);

        updateTAG();
    }

    protected void initListener() {
        gv.setOnItemClickListener(this);
        addTag.setOnClickListener(this);
        knotageditLl.setOnClickListener(this);
        tag0.setOnClickListener(this);
        tag1.setOnClickListener(this);
        tag2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.kno_tag_edit_ll:
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                knotageditLl.requestFocus();
                break;
            case R.id.tv_tag_add:
                addTag();
                break;
            case R.id.tv_tag_0:
                changSelectedTagBg(tag0);
                break;
            case R.id.tv_tag_1:
                changSelectedTagBg(tag1);
                break;
            case R.id.tv_tag_2:
                changSelectedTagBg(tag2);
                break;
        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        saveTags();
    }

    /**
     * 保存标签
     */
    private void saveTags() {
        showLoadingIndicator();
        UserController.setTags(selectTags);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadProfileEvent(UploadProfileEvent event) {
        if (isFinishing())
            return;
        switch (event.state) {
            case DataEvent.SUCC:
                ToastUtils.toastMessage(PersonalTagActivity.this, getString(R.string.modify_success));

                AccountManager.getInstance().updateAccount(AccountManager.NameKey.TAGS, getTagsStr());
                finish();
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(PersonalTagActivity.this, getString(R.string.modify_fail));
                break;
        }
        hideLoadingIndicator();
    }

    /**
     * 用户标签内容
     *
     * @return
     */
    private String getTagsStr() {
        String str = "";
        for (String s : selectTags) {
            str = str + s + ";";
        }
        if (!CollectionUtils.isEmpty(selectTags)) {
            return str.substring(0, str.length() - 1);
        } else {
            return str;
        }
    }

    private void changSelectedTagBg(TextView tag) {
        if (StringUtils.isNotEmpty(tag.getText().toString())) {
            selectTags.remove(tag.getText().toString());
            tag.setText("");
            changTagStyle(tag, false);
            updateTAG();
            adapter.notifyDataSetChanged();
        }
    }

    private void updateTAG() {
        for (TextView textView : tagArr) {
            textView.setText("");
            changTagStyle(textView, false);
        }
        for (int i = 0; i < selectTags.size(); i++) {
            tagArr[i].setText(selectTags.get(i));
            changTagStyle(tagArr[i], true);
        }
    }

    /**
     * 添加自定义标签
     */
    private void addTag() {
        String addText = addTagEt.getText().toString().trim();
        if (selectTags.size() == 3) {
            imm.hideSoftInputFromWindow(addTagEt.getWindowToken(), 0);
            ToastUtils.toastMessage(this, getString(R.string.tag_up_limit));
            return;
        } else if (StringUtils.isEmpty(addText)) {
            ToastUtils.toastMessage(this, getString(R.string.tag_not_empty));
        } else if (selectTags.contains(addText)) {
            imm.hideSoftInputFromWindow(addTagEt.getWindowToken(), 0);
            ToastUtils.toastMessage(this, getString(R.string.tag_not_same));
            addTagEt.setText("");
            return;
        } else {
            for (TextView text : tagArr) {
                if (TextUtils.isEmpty(text.getText())) {
                    text.setText(addText);
                    addTagEt.setText("");
                    changTagStyle(text, true);
                    selectTags.add(addText);
                    break;
                }
            }
        }
        imm.hideSoftInputFromWindow(addTagEt.getWindowToken(), 0);
    }

    /**
     * gv的显示
     */
    class KnoTagsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return allTags.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = View.inflate(PersonalTagActivity.this,
                        R.layout.gridview_item_tags, null);
            }
            TextView view = (TextView) convertView
                    .findViewById(R.id.gv_item_tv);
            String stringtag = allTags.get(position);
            view.setText(stringtag);
            if (selectTags.contains(stringtag)) {
                changTagStyle(view, true);
            } else {
                view.setTag("");
                changTagStyle(view, false);
            }
            return convertView;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        //只做添加处理
        if (selectTags.size() == 3) {
            ToastUtils.toastMessage(this, getString(R.string.tag_up_limit));
        } else if (selectTags.contains(allTags.get(position))) {
            ToastUtils.toastMessage(this, getString(R.string.tag_not_same));
        } else {
            for (TextView text : tagArr) {
                if (TextUtils.isEmpty(text.getText())) {
                    text.setText(allTags.get(position));
                    changTagStyle(text, true);
                    selectTags.add(allTags.get(position));
                    adapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    /**
     * 改变TAG背景和字体颜色
     *
     * @param view
     * @param flag
     */
    private void changTagStyle(TextView view, boolean flag) {
        if (flag) {
            view.setBackgroundResource(R.drawable.tag_txt_shape_selected);
            view.setTextColor(Color.WHITE);
        } else {
            view.setBackgroundResource(R.drawable.tag_txt_shape);
            view.setTextColor(Color.BLACK);
        }
    }

    @Override
    public void onBackPressed() {
        if (isEqualList()) {
            super.onBackPressed();
        } else {
            cancelEditAlert();
        }

    }

    private boolean isEqualList() {
        //标签个数改变、或 内容改变
        return selectTags.size() == getOriginTag().size() && judgeContent();

    }

    private boolean judgeContent() {
        for (int i = 0; i < getOriginTag().size(); i++) {
            if (!selectTags.contains(getOriginTag().get(i)))
                return false;
        }
        return true;
    }

    private List<String> getOriginTag() {
        List<String> originSelectTags = new ArrayList<>();
        Account account = AccountManager.getInstance().getAccount();
        String tags = account.tags.toString().trim();
        if (!StringUtils.isEmpty(tags)) {
            String[] str = tags.split(";");
            for (String a : str) {
                originSelectTags.add(a);
            }
        }
        return originSelectTags;
    }

    public void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.giveup_edit))
                .setMessage(getString(R.string.giveup_edit_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        finish();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }
}
